package com.simple.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hankcs.hanlp.seg.Dijkstra.DijkstraSegment;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.seg.common.Term;
import com.simple.mapper.ocrmark.EsMarkMapper;
import com.simple.mapper.ocrmark.OcrQuestionMarkMapper;
import com.simple.mapper.nrmp.QuestionAfantiMapper;
import com.simple.mapper.nrmp.QuestionMapper;
import com.simple.question.Question;
import com.simple.search.QuestionSearch;
import com.simple.util.*;
import com.simple.vo.AFanTi;
import com.simple.vo.SearchQuestionResult;
import com.simple.vo.WordRegionList;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 有道OCR题目搜索服务
 * @author lub
 */
@Service
public class QuestionSearchService {
	
    private static String reg = "[\u4e00-\u9fa5]";
    
    private static Pattern pat = Pattern.compile(reg);
    
    private static Set<String> fuhaoSet = new HashSet<>();
    
    private static String[] fuhaoArray = {",", ".", ";", ":", "?", "，", "。", "：", "；", "？", "“", "”", "…", "、", "\n", "　", "!", "\r"};
    
    private static float similar = 0.5f;

    @Value("${ocrmark.imgPath}")
    private String imgPath;// = "D:\\2.OCR_TXT\\searchImage\\";

	private String titles[] = {"图片名称","图片是否有效(1有效0无效)","是否搜索成功(1成功)","是否指搜图(1是)","搜索正确题目位置","搜索正确题目ID","是否已标记(1已标)"};


    static {
    	for(int i = 0; i < fuhaoArray.length; i++) {
        	fuhaoSet.add(fuhaoArray[i]);
    	}
    	try {
    		String similarString = "0.6";
    		float similarTemp = Float.parseFloat(similarString);
    		if(similarTemp >= 0.1f && similarTemp <= 0.9f) {
    			similar = similarTemp;
    		}
    	}
    	catch(Exception e) {
    		
    	}
    }
    
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionAfantiMapper questionAfantiMapper;
    @Autowired
    private OcrQuestionMarkMapper ocrQuestionMarkMapper;



	public void zip(HttpServletResponse response,String type){
		List<Map<String,Object>>  data = null;
		switch(type) {
			case "valid":
				data = ocrQuestionMarkMapper.queryIsMarkValid();
				break;
			case "invalid":
				data = ocrQuestionMarkMapper.queryIsMarkInValid();
				break;
			case "pointvalid":
				data = ocrQuestionMarkMapper.queryIsMarkPointValid();
				break;
			case "nopointvalid":
				data = ocrQuestionMarkMapper.queryIsMarkNoPointValid();
				break;
			case "nosearch":
				data = ocrQuestionMarkMapper.queryIsMarkNoSearch();
				break;
			case "pointnosearch":
				data = ocrQuestionMarkMapper.queryIsMarkPointNoSearch();
				break;
			case "nopointnosearch":
				data = ocrQuestionMarkMapper.queryIsMarkNoPointNoSearch();
				break;
			case "success":
				data = ocrQuestionMarkMapper.queryIsMarkSuccess();
				break;
			case "pointsuccess":
				data = ocrQuestionMarkMapper.queryIsMarkPointSuccess();
				break;
			case "nopointsuccess":
				data = ocrQuestionMarkMapper.queryIsMarkNoPointSuccess();
				break;
			case "first":
				data = ocrQuestionMarkMapper.queryIsMarkSuccessFirst();
				break;
			case "pointfirst":
				data = ocrQuestionMarkMapper.queryIsMarkPointSuccessFirst();
				break;
			case "nopointfirst":
				data = ocrQuestionMarkMapper.queryIsMarkNoPointSuccessFirst();
				break;
			case "nofirst":
				data = ocrQuestionMarkMapper.queryIsMarkSuccessNoFirst();
				break;
			case "pointnofirst":
				data = ocrQuestionMarkMapper.queryIsMarkPointSuccessNoFirst();
				break;
			case "nopointnofirst":
				data = ocrQuestionMarkMapper.queryIsMarkNoPointSuccessNoFirst();
				break;
		}

		ZIPUtil.zip(data,imgPath,response,type);
	}

    public void exportExecl(HttpServletResponse response) throws Exception {

		long count = queryAllCount();
		int pageSize = 5000;
		int page = 0;
        if(count%pageSize==0){
			page = (int)count/pageSize;
		}else{
			page = (int)count/pageSize + 1;
		}
		Workbook workbook = new XSSFWorkbook();
        for(int i=0; i<page; i++){
			PageInfo<Map<String,Object>> pageData = queryAll(i, pageSize);
			List<Map<String,Object>> data = pageData.getList();
			ExportExecl.export(workbook,titles,data,(i+1)+"");
		}
		OutputStream out = response.getOutputStream();
		download(workbook,response);
		out.flush();
		out.close();
	}



	public void download(Workbook workbook ,HttpServletResponse response){
		try {
			String fileName = "data.xlsx";
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			workbook.write(os);
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// 设置response参数，可以打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName).getBytes(), "iso-8859-1"));
			ServletOutputStream out = response.getOutputStream();
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			try {
				bis = new BufferedInputStream(is);
				bos = new BufferedOutputStream(out);
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
			} catch (final IOException e) {
				throw e;
			} finally {
				if (bis != null)
					bis.close();
				if (bos != null)
					bos.close();
			}
		}catch (Exception e){
			e.printStackTrace();
		}

	}


	public PageInfo<Map<String,Object>> queryAll(int pageNum, int pageSize){
		PageHelper.startPage(pageNum,pageSize);
		return new PageInfo<Map<String,Object>>(ocrQuestionMarkMapper.queryAll());
	}


   public List<Map<String,Object>> queryAll(){
    	return ocrQuestionMarkMapper.queryAll();
   }

	public long queryAllCount(){
		return ocrQuestionMarkMapper.queryAllCount();
	}



	public int unlockMarking(){
	    return ocrQuestionMarkMapper.unlockMarking();
    }


	public Map getDeal(){
		Map map = new HashMap();
		map.put("totalCount",ocrQuestionMarkMapper.queryAllCount());
        map.put("isMarkCount",ocrQuestionMarkMapper.queryIsMarkCount());
		map.put("noMarkCount",ocrQuestionMarkMapper.queryNoMarkCount());
		return map;
	}



    
    public Map getOneImg() {
    	Map map = new HashMap();
    	String img = ocrQuestionMarkMapper.getOneImg();
    	if(img != null && !"".equals(img)) {
    		ocrQuestionMarkMapper.marking(img);
    	}else{
    		return null;
		}
		map.put("name",img);
        String filePath = imgPath + img;
        if(!new File(filePath).exists()){
			System.err.println(filePath+" 服务器文件不存在........................");
        	return null;
		}
		byte[] bytes = getBytes(new File(filePath));
		org.apache.commons.codec.binary.Base64 base64 = new  org.apache.commons.codec.binary.Base64();
		String imgBase64 = base64.encodeToString(bytes);
		map.put("imgBase64","<img src=\"data:image/jpeg;base64," + imgBase64 + "\" width=\"800\" height=\"300\">");
    	return map;
    }

	public static byte[] getBytes(File file) {
		byte[] buffer = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			// picture max size is 2MB
			ByteArrayOutputStream bos = new ByteArrayOutputStream(2000 * 1024);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}
    
    public void updateMark(Map map) {
    	ocrQuestionMarkMapper.updateMark(map);
    }
    
    
    public void invalid(String img) {
        ocrQuestionMarkMapper.invalid(img);
    }



	public void initData(String img) {
    	ocrQuestionMarkMapper.initInsert(img);
	}


	public void initData(List<String> imgs) {
    	ocrQuestionMarkMapper.insertBatch(imgs);
	}



	public JSONArray esQuestionByImageUp(File file) throws Exception {
		String ocr = OCRYouDaoUtil.ocr(getImageStr(file));
		String ocrRs = handleOcr(ocr);
		return QuestionSearch.searchText(ocrRs);

	}


	public JSONArray esQuestionByText(String text) throws Exception {
		return QuestionSearch.searchText(text);

	}




	public String ocrQuestionByImageUp(String fileName) throws Exception {
		String ocr = OCRYouDaoUtil.ocr(getLocalFileBase64(fileName));
		return handleOcr(ocr);
	}

	public String ocrQuestionByImageUp(File file) throws Exception {
		String ocr = OCRYouDaoUtil.ocr(getImageStr(file));
		return handleOcr(ocr);

	}


	public JSONArray esQuestionByImageUp(String baseFile) throws Exception {
		String ocr = OCRYouDaoUtil.ocr(baseFile);
		String ocrRs = handleOcr(ocr);
		return QuestionSearch.searchText(ocrRs);
	}





	public void initData() {
		List<String> imgs = new ArrayList<>();
		File dir = new File(imgPath);
		for(File img : dir.listFiles()){
			imgs.add(img.getName());
		}
		System.out.println("insert begin...");
		long start = System.currentTimeMillis();
		ocrQuestionMarkMapper.insertBatch(imgs);
		System.out.println("insert [" + imgs.size() + "] use time:" +(System.currentTimeMillis()-start) + "ms");
	}



	public String getLocalFileBase64 (String fileName){
		String filePath = imgPath + fileName;
		String imageBase64 = getImageStr(new File(filePath));
		return imageBase64;
	}


	public String getNrmpText(String img_name){
        Map<String, String> paramMap = new HashMap<String, String>();
        String imageBase64 = getLocalFileBase64(img_name);
        paramMap.put("image", imageBase64);
        String resultText = HttpUtil.post("https://resource.youxuepai.com/ures/parseService/question/youXueGetResult", 10000, paramMap);
        return resultText;
    }


	/**
	 * 网页版测试搜索结果用，请不要调用
	 */
	public String searchQuestionByImageHttp(String fileName) throws Exception {
		String imageBase64 = getLocalFileBase64(fileName);
		Map map = new HashMap();
		map.put("image",imageBase64);
		return HttpUtil.post("https://newresource.youxuepai.com/ures/parseService/question/youXueGetResult",10000,map);
	}

	public List<JSONObject> searchQuestionByImageForPointHttp(String fileName) throws Exception {
		String imageBase64 = getLocalFileBase64(fileName);

		return null;
	}




	/**
	 * 网页版测试搜索结果用，请不要调用
	 */
	public List<JSONObject> searchQuestionByImageForTest(String fileName,File file) throws Exception {
		String imageBase64 = null;
		if(null != fileName){
			 imageBase64 = getLocalFileBase64(fileName);
		}else{
			 imageBase64 = getImageStr(file);
		}
		//String imageBase64 = getImageStr(cacheFile);
		String ocr = OCRYouDaoUtil.ocr(imageBase64);
		//List<SearchQuestionResult> resultList = searchQuestionIdsYoudaoAFanOcr(ocr, OCRAFanTiUtil.ocr(imageBase64), 0);
		String result = handleOcr(ocr);
		System.out.println(result);
		List<JSONObject> questionList = new ArrayList<>();
		JSONObject originObject = new JSONObject();
		originObject.put("id", 0);
		originObject.put("trunk", "<img src=\"data:image/jpeg;base64," + imageBase64 + "\">");
		questionList.add(originObject);
		JSONObject searchObject = new JSONObject();
		searchObject.put("id", -1);
		searchObject.put("trunk", result);
		questionList.add(searchObject);
		/*if(result != null) {
			JSONArray resultArray = QuestionSearch.searchText(result);
			resultArray = removeByResourceTypeId(resultArray, 10);
			for(int i = 0; i < resultArray.size(); i++) {
				JSONObject questionObject = new JSONObject();
				JSONObject indexObject = resultArray.getJSONObject(i).getJSONObject("_source");
				questionObject.put("id", indexObject.getLong("id"));
				questionObject.put("trunk", indexObject.getString("text"));
				questionList.add(questionObject);
			}
		}*/

        if(result != null) {
            List<SearchQuestionResult> resultList = searchQuestionIdsYoudaoAFanOcr(ocr,OCRAFanTiUtil.ocr(imageBase64) , 0);
            for(int i = 0; i < resultList.size(); i++) {
                JSONObject questionObject = new JSONObject();
                SearchQuestionResult questionResut = resultList.get(i);
                questionObject.put("type", questionResut.getType());
                if(questionResut.getType() == 0) {
                    questionObject.put("id", questionResut.getQuestionId());
                }
                else {
                    questionObject.put("trunk", questionResut.getaFanTi().getTrunkHtml());
                    questionObject.put("analys", questionResut.getaFanTi().getAnalysHtml());
                    questionObject.put("answer", questionResut.getaFanTi().getAnswerHtml());
                }
                questionList.add(questionObject);
            }
        }


		return questionList;
	}


	/**
	 * 网页版测试搜索结果用，请不要调用
	 */
	public List<JSONObject> searchQuestionByImageForPointTest(String fileName,File file) throws Exception {
		//String imageBase64 = getImageStr(cacheFile);
		//String imageBase64 = getLocalFileBase64(fileName);
		String imageBase64 = null;
		if(null != fileName){
			imageBase64 = getLocalFileBase64(fileName);
		}else{
			imageBase64 = getImageStr(file);
		}
		String ocr = OCRYouDaoUtil.ocr(imageBase64);
		Dimension dimension = null;
		if(imageBase64.startsWith("/9")) {
			dimension = ImageUtil.getJPGImageDimmension(Base64.decode(imageBase64));
		}
		else {
			dimension = ImageUtil.getPNGImageDimmension(Base64.decode(imageBase64));
		}
		List<WordRegionList> wordRegionListArray = WordRegionUtil.handleOcr(ocr,(int)dimension.getWidth(), (int)dimension.getHeight());
		List<String> supposeTexts = new ArrayList<>();
		for(WordRegionList wordRegionList: wordRegionListArray) {
			String text = handleOcr(ocr, wordRegionList);
			supposeTexts.add(text);
		}
		String result = supposeTexts.get(supposeTexts.size() - 1);
		for(String text: supposeTexts) {
			System.out.println(text);
		}
		List<JSONObject> questionList = new ArrayList<>();
		JSONObject originObject = new JSONObject();
		originObject.put("id", 0);
		originObject.put("trunk", "<img src=\"data:image/jpeg;base64," + imageBase64 + "\">");
		questionList.add(originObject);
		JSONObject searchObject = new JSONObject();
		searchObject.put("id", -1);
		searchObject.put("trunk", result);
		questionList.add(searchObject);
		if(result != null) {
			JSONArray resultArray = QuestionSearch.searchTextMulti(supposeTexts);
			resultArray = removeByResourceTypeId(resultArray, 10);
			for(int i = 0; i < resultArray.size(); i++) {
				JSONObject questionObject = new JSONObject();
				JSONObject indexObject = resultArray.getJSONObject(i).getJSONObject("_source");
				questionObject.put("id", indexObject.getLong("id"));
				questionObject.put("trunk", indexObject.getString("text"));
				questionList.add(questionObject);
			}
		}
		return questionList;
	}



	private JSONArray removeByResourceTypeId(JSONArray resultArray, int resourceTypeId) {
		if(resultArray.isEmpty()) {
			return resultArray;
		}
		List<Long> questionIds = new ArrayList<>(resultArray.size());
		for(int i = 0; i < resultArray.size(); i++) {
			JSONObject indexObject = resultArray.getJSONObject(i).getJSONObject("_source");
			long id = indexObject.getLong("id");
			questionIds.add(id);
		}
		List<Question> questionList = questionMapper.selectByIdList(questionIds);
		Map<Long, Integer> typeMap = new HashMap<>();
		for(Question question: questionList) {
			if(question.getResourceTypeId() != resourceTypeId) {
				typeMap.put(question.getId(), question.getResourceTypeId());
			}
		}
		JSONArray newArray = new JSONArray();
		for(int i = 0; i < resultArray.size(); i++) {
			JSONObject indexObject = resultArray.getJSONObject(i).getJSONObject("_source");
			long id = indexObject.getLong("id");
			if(typeMap.containsKey(id)) {
				newArray.add(resultArray.getJSONObject(i));
			}
		}
		return newArray;
	}


	/**
	 * 根据有道ocr返回的原始json数据，和阿凡题ocr返回的json数据，和科目subjectId搜题， subjectId为0的时候为所有的科目，返回0-5题数据
	 * @param ocr 有道ocr结果
	 * @param aFanTiOcr 阿凡题ocr结果
	 * @param subjectId 科目id
	 * @return
	 */
	public List<SearchQuestionResult> searchQuestionIdsYoudaoAFanOcr(String ocr, String aFanTiOcr, long subjectId) {
		long time = System.currentTimeMillis();
		String result = handleOcr(ocr);
		List<SearchQuestionResult> questionList = new ArrayList<>();
		System.out.println("afantiOcr="+aFanTiOcr);
		AFanTi aFanTi = handleAFanTiResult(aFanTiOcr);
		System.out.println("aFanTi==null-->"+(aFanTi==null));
		if(aFanTi != null && subjectId != 0) {
			if(subjectId != aFanTi.getSubjectId()) {
				aFanTi = null;
			}
		}
		if(result != null) {
			JSONArray resultArray = null;
			if(subjectId == 0) {
				resultArray = QuestionSearch.searchText(result);
			}
			else {
				resultArray = QuestionSearch.searchTextSubject(result, subjectId);
			}
			resultArray = removeByResourceTypeId(resultArray, 10);
			if(aFanTi != null) { //假如阿凡题的题目的科目跟搜出来的题目的大部分的科目id不同，那么就认为没有搜到。
				Map<Long, Integer> countMap = new LinkedHashMap<>();
				for(int i = 0; i < resultArray.size() && questionList.size() < 5; i++) {
					JSONObject indexObject = resultArray.getJSONObject(i).getJSONObject("_source");
					long questionSubjectId = indexObject.getLong("subjectId");
					Integer count = countMap.get(questionSubjectId);
					if(count == null) {
						count = 0;
					}
					count++;
					countMap.put(questionSubjectId, count);
				}
				int maxCount = 0;
				long maxSubjectId = 0;
				for(long key: countMap.keySet()) {
					if(countMap.get(key) > maxCount) {
						maxSubjectId = key;
						maxCount = countMap.get(key);
					}
				}
				if(maxSubjectId != 0 && maxSubjectId != aFanTi.getSubjectId()) {
					aFanTi = null;
				}
			}
			if(resultArray.size() > 0) {
				for(int i = 0; i < resultArray.size() && questionList.size() < 5; i++) {
					JSONObject indexObject = resultArray.getJSONObject(i).getJSONObject("_source");
					long id = indexObject.getLong("id");
					if (i == 0 && aFanTi != null) {
//						String trunkHtml = aFanTi.getTrunkHtml();
//						Document doc = Jsoup.parse(trunkHtml);
//						doc.body().children().get(0).prepend("<span style=\"color: red;\">(阿凡题)</span><br>");
//						trunkHtml = doc.html();
//						aFanTi.setTrunkHtml(trunkHtml);
						String text = indexObject.getString("text");
						float score = CompareTextUtil.compare(text, result);
						if(score > similar || aFanTi.getKnowledgePointId() == null) {
							questionList.add(new SearchQuestionResult(id));
							questionList.add(new SearchQuestionResult(aFanTi));
						}
						else {
							questionList.add(new SearchQuestionResult(aFanTi));
							questionList.add(new SearchQuestionResult(id));
						}
					}
					else {
						questionList.add(new SearchQuestionResult(id));
					}
				}
			}
			else if(aFanTi != null){
				questionList.add(new SearchQuestionResult(aFanTi));
			}
		}
		System.out.println("soutiMill="+(System.currentTimeMillis() - time) + "ms");
		return questionList;
	}


	private AFanTi handleAFanTiResult(String ocr) {
		JSONObject jsonObject = JSON.parseObject(ocr);
		if(jsonObject.getJSONObject("meta").getIntValue("status") != 0) {
			return null;
		}
		JSONObject result = jsonObject.getJSONObject("data").getJSONObject("search_result");
		if(result.getIntValue("is_figured_out") != 1) {
			return null;
		}
		AFanTi aFanTi = new AFanTi();
		aFanTi.setSubjectName(result.getString("subject"));
		// aFanTi.setKnowledgePointName(result.getString("knowledge_point"));
		String html = result.getString("answer_html_content");
		aFanTi.setTrunkHtml(OCRAFanTiUtil.getAFanTiTrunk(html));
		aFanTi.setAnalysHtml(OCRAFanTiUtil.getAFanTiAnalys(html));
		aFanTi.setAnswerHtml(OCRAFanTiUtil.getAFanTiAnswer(html));
		JSONObject infoObject = result.getJSONObject("unified_label");
		if(infoObject != null) {
			if(infoObject.containsKey("subject")) {
				aFanTi.setSubjectName(infoObject.getJSONObject("subject").getString("name"));
			}
			if(infoObject.containsKey("knowledge_point")) {
				aFanTi.parseKnowledge(infoObject.getJSONArray("knowledge_point"));
			}
		}
		String s = "window.question_id = \"";
		int questionIdStart = html.indexOf(s);
		if(questionIdStart == -1) {
			return null;
		}
		questionIdStart += s.length();
		int questionIdEnd = html.indexOf("\"", questionIdStart + 1);
		if(questionIdEnd == -1) {
			return null;
		}
		aFanTi.setQuestionId(Long.parseLong(html.substring(questionIdStart,questionIdEnd)));
		aFanTi.setOrigin(ocr);
		if(questionAfantiMapper.getById(aFanTi.getQuestionId()) == null) {
			try {
				//questionAfantiMapper.save(aFanTi);
			}
			catch(Exception e) {
				e.printStackTrace();
			}
		}
		else {
			//questionAfantiMapper.update(aFanTi);
		}
		return aFanTi;
	}
	private static String handleOcr(String ocr) {
		return handleOcr(ocr, null);
	}

	private static String handleOcr(String ocr, WordRegionList wordRegionList) {
		System.out.println(ocr);
		JSONObject ocrObject = JSON.parseObject(ocr);
		if(!ocrObject.getString("errorCode").equals("0")) {
			System.err.println(ocr);
			return null;
		}
		JSONArray regionArray = ocrObject.getJSONObject("Result").getJSONArray("regions");
		if (regionArray == null || regionArray.size() == 0) {
			return null;
		}
		int regionCount = regionArray.size();
		List<String> textList = new ArrayList<String>();
		for (int i = 0; i < regionCount; i++) { // 块
			StringBuffer textBuffer = new StringBuffer();
			JSONObject regionObj = (JSONObject)regionArray.get(i);
			JSONArray lineArray = regionObj.getJSONArray("lines");
			if (lineArray == null || lineArray.size() == 0) {
				continue;
			}
			int lineCount = lineArray.size();
			boolean lastIsChinese = false;
			for (int j = 0; j < lineCount; j++) { // 行
				JSONArray tmpArray = (JSONArray)lineArray.get(j);
				if (tmpArray == null || tmpArray.size() == 0) {
					continue;
				}
				for (int k = 0; k < tmpArray.size(); k++) {
					JSONObject obj = tmpArray.getJSONObject(k);
					if(wordRegionList == null || wordRegionList.getRegionMap().containsKey(obj.getString("boundingBox"))) {
						String text = obj.getString("text");
						String type = obj.getString("type");
						if (type.equals("formula")) {
							text = text.replaceAll("si\\s*([\\\\^{])", "sin$1")
									.replaceAll("co\\s*([\\\\^{])", "cos$1")
									.replaceAll("\\{}", " ")
									.trim();
							while (text.endsWith("{")) {
								text = text.substring(0, text.length() - 1).trim();
							}
							textBuffer.append(" "+ text+" ");
							lastIsChinese = false;
						} else {
							if(k == 0) {
								if(lastIsChinese && text.length() > 0) {
									lastIsChinese = false;
									String word = text.substring(0, 1);
									if(containChinese(word)) {
										textBuffer.append(text);
									}
									else {
										textBuffer.append(" "+text);
									}
								}
								else {
									textBuffer.append(" "+text);
								}
							}
							else {
								textBuffer.append(text);
							}
						}
					}
				}
				lastIsChinese = false;
				if(textBuffer.length() > 0) {
					String word = textBuffer.substring(textBuffer.length() - 1);
					if(containChinese(word)) {
						lastIsChinese = true;
					}
				}
			}
			if(textBuffer.length() > 0) {
				String text = textBuffer.toString();
				text = text.replace("÷", " ÷ ");
				text = text.replace("^ { \\prime }", "'");
				text = text.replace("^ { \\prime \\prime }", "\"");
				text = text.replace("\\prime", " ' ");
				text = text.replace("\\angle", " ∠ ");
				text = text.replace("\\triangle", " △ ");
				text = text.replace("\\Delta", " △ ");
				text = text.replace("\\pm", " ± ");
				text = text.replace("\\subseteq", " ≌ ");
				text = text.replace("\\odot", " ⊙ ");
				text = text.replace("\\approx", " ≈ ");
				text = text.replace("\\leq", " ≤ ");
				text = text.replace("\\geq", " ≥ ");
				text = text.replace("\\neq", " ≠ ");
				text = text.replace("\\perp", " ⊥ ");
				text = text.replace("\\bot", " ⊥ ");
				text = text.replace("\\cap", " ∩ ");
				text = text.replace("\\cup", " ∪ ");
				text = text.replace("\\}", "}");
				text = text.replace("\\{", "{");
				text = text.replace("∠", " ∠ ");

				if(text.contains(" \\alpha ")) {
					text = text.replace(" \\alpha ", " a");
				}
				text = text.replace("\\alpha", " a");
				if(text.contains(" \\beta ")) {
					text = text.replace(" \\beta ", " B");
				}
				text = text.replace("\\beta", " B");
				if(text.contains(" \\gamma ")) {
					text = text.replace(" \\gamma ", " y");
				}
				text = text.replace("\\gamma", " y");
				if(text.contains(" \\pi ")) {
					text = text.replace(" \\pi ", "π");
				}
				text = text.replace("\\pi", "π");
				text = text.replace("\\quad", "");
				text = text.replace("\\div", " ÷ ");
				text = text.replace("\\times", " x ");
				text = text.replace("\\circ", " ° ");
				text = text.replace("\\cdot", "");
				text = text.replace("\\log", "log");
				text = text.replace("\\tan", "tan");
				text = text.replace("\\sin", "sin");
				text = text.replace("\\cos", "cos");

				text = text.replace("\\infty", " ∞ ");
				text = text.replace("\\in", " ∈ ");
				text = text.replace("≈", " ≈ ");
				text = text.replace("=", " = ");
				text = text.replace("~", " - ");
				text = text.replace("-", " - ");
				text = text.replace("+", " + ");
				text = text.replace("(", " ( ");
				text = text.replace(")", " ) ");
				text = text.replace("<", " < ");
				text = text.replace(">", " > ");
				text = text.replace("[", " [ ");
				text = text.replace("]", " ] ");
				text = text.replace("|", " | ");
				text = text.replace("{", " { ");
				text = text.replace("}", " } ");
				text = text.replace("/", " / ");
				text = text.replace("°", " ° ");
				text = text.replace("/   /", " // ");
				text = text.replace("/  /", " // ");
				text = text.replace("/ /", " // ");
				text = text.replace("^", " ^ ");
				text = text.replace("_", " _ ");

				Pattern p = Pattern.compile("\\\\mathrm|\\\\mathbf");
				Matcher m = p.matcher(text);
				while(m.find()) {
					int start = m.start();
					int middle = text.indexOf("{", start);
					int end = text.indexOf("}", start);
					text = text.substring(0, start) + text.substring(middle + 1, end).replace("~", "") + text.substring(end + 1);
					m = p.matcher(text);
				}
				text = text.replace("A.", " ");
				text = text.replace("B.", " ");
				text = text.replace("C.", " ");
				text = text.replace("D.", " ");
				textList.add(text);
			}
		}
		String returnText = "";
		for(String text: textList) {
			List<String> segList = getSegText(text);
			for(String s: segList) {
				returnText += " " + s;
			}
		}

		Pattern p = Pattern.compile("[0-9][\\+\\-x÷/][0-9]");
		StringBuffer buffer = new StringBuffer(returnText);
		Matcher m = p.matcher(buffer);
		while(m.find()) {
			buffer.replace(m.start()+1, m.end()-1, " "+buffer.substring(m.start()+1, m.end()-1)+" ");
			m = p.matcher(buffer);
		}

		p = Pattern.compile("[^0-9][\\+\\-x÷/][0-9]");
		m = p.matcher(buffer);
		while(m.find()) {
			buffer.replace(m.start()+1, m.end()-1, " "+buffer.substring(m.start()+1, m.end()-1)+" ");
			m = p.matcher(buffer);
		}

		p = Pattern.compile("[0-9][\\+\\-÷/][^0-9]");
		m = p.matcher(buffer);
		while(m.find()) {
			buffer.replace(m.start()+1, m.end()-1, " "+buffer.substring(m.start()+1, m.end()-1)+" ");
			m = p.matcher(buffer);
		}
		returnText = buffer.toString();
		returnText = returnText.replace("      ", " ");
		returnText = returnText.replace("     ", " ");
		returnText = returnText.replace("    ", " ");
		returnText = returnText.replace("   ", " ");
		returnText = returnText.replace("  ", " ");
		returnText = returnText.replace("( )", "");
		returnText = returnText.replace("^ { ° }", " ° ");
		returnText = returnText.replace("sqrt { 3 } {", "sqrt [ 3 ] {");
		returnText = returnText.replace("sqrt { 4 } {", "sqrt [ 4 ] {");
		returnText = returnText.replace("sqrt { 5 } {", "sqrt [ 5 ] {");
		returnText = returnText.replace("点 0", "点 O");
		returnText = returnText.replace("圆 0", "圆 O");
		returnText = returnText.replace("  ", " ");
		String[] searchTextArray = returnText.split(" ");
		String searchTemp = returnText;
		if(searchTextArray.length > 250) {
			searchTemp = "";
			for(int i = 0; i < 250; i++) {
				searchTemp += " " + searchTextArray[i];
			}
			searchTemp = searchTemp.trim();
		}
		return handleDanwei(searchTemp);
	}

	private static String handleText(String text) {
		text = text.replace("÷", " ÷ ");
		text = text.replace("×", " x "); //乘号变成x
		text = text.replace("+", " + ");
		text = text.replace("-", " - ");
		text = text.replace("/", " / ");
		text = text.replace("−", " - ");
		text = text.replace("—", " - ");
		text = text.replace("=", " = ");
		text = text.replace("±", " ± ");
		text = text.replace("(", " ( ");
		text = text.replace(")", " ) ");
		text = text.replace("<", " < ");
		text = text.replace(">", " > ");
		text = text.replace("○", " ○ ");
		text = text.replace("[", " [ ");
		text = text.replace("]", " ] ");
		text = text.replace("|", " | ");
		text = text.replace("│", " | ");
		text = text.replace("·", " · ");
		text = text.replace("□", " □ ");
		text = text.replace("≈", " ≈ ");
		text = text.replace("~", " - ");
		text = text.replace("≤", " ≤ ");
		text = text.replace("≠", " ≠ ");
		text = text.replace("≥", " ≥ ");
		text = text.replace("≦", " ≤ ");
		text = text.replace("≧", " ≥ ");
		text = text.replace("°", " ° ");
		text = text.replace("′", " ' ");
		text = text.replace("″", " \" ");
		text = text.replace("∠", " ∠ ");
		text = text.replace("△", " △ ");
		text = text.replace("//", " // ");
		text = text.replace("/ /", " // ");
		text = text.replace("/  /", " // ");
		text = text.replace("/   /", " // ");
		text = text.replace("∥", " // ");
		text = text.replace("‖", " // ");
		text = text.replace("⊥", " ⊥ ");
		text = text.replace("≌", " ≌ ");
		text = text.replace("⊙", " ⊙ ");
		text = text.replace("•", " • ");
		text = text.replace("→", " → ");
		text = text.replace("⇌", " ⇌ ");
		text = text.replace("↑", " ↑ ");
		text = text.replace("☉", " ☉ ");
		text = text.replace("∈", " ∈ ");
		text = text.replace("∞", " ∞ ");
		String returnText = "";
		List<String> segList = getSegText(text);
		int count = 0;
		for(String s: segList) {
			count++;
			returnText += " " + s;
			if(count >= 250) {
				break;
			}
		}
		return handleDanwei(returnText.trim());
	}

	private static List<String> getSegText(String text){
		List<String> textList = new ArrayList<>();
		char[] charList = text.toCharArray();
		StringBuilder buffer = new StringBuilder();
		boolean hanziFlag = true;
		Segment nShortSegment = new DijkstraSegment().enableCustomDictionary(false).enableAllNamedEntityRecognize(true);
		for(char c : charList) {
			if(buffer.length() == 0) {
				if(containChinese(c+"")) {
					hanziFlag = true;
					buffer.append(c);
				}
				else if(fuhaoSet.contains(c+"")) {

				}
				else {
					hanziFlag = false;
					buffer.append(c);
				}
			}
			else {
				if(containChinese(c+"")) {
					if(hanziFlag) {
						buffer.append(c);
					}
					else {
						String notHanzi = buffer.toString();
						textList.add(notHanzi);
						buffer = new StringBuilder();
						buffer.append(c);
						hanziFlag = true;
					}
				}
				else if(fuhaoSet.contains(c+"")) {
					if(hanziFlag) {
						String hanzi = buffer.toString();
						List<Term> termList = nShortSegment.seg(hanzi);
						String s = "";
						for(Term term: termList) {
							s += " " + term.word;
						}
						textList.add(s.trim());
					}
					else {
						String notHanzi = buffer.toString();
						textList.add(notHanzi);
					}
					buffer = new StringBuilder();
				}
				else {
					if(hanziFlag) {
						String hanzi = buffer.toString();
						List<Term> termList = nShortSegment.seg(hanzi);
						String s = "";
						for(Term term: termList) {
							s += " " + term.word;
						}
						textList.add(s.trim());
						buffer = new StringBuilder();
						buffer.append(c);
						hanziFlag = false;
					}
					else {
						buffer.append(c);
					}
				}
			}
		}
		if(buffer.length() > 0) {
			if(hanziFlag) {
				String hanzi = buffer.toString();
				List<Term> termList = nShortSegment.seg(hanzi);
				String s = "";
				for(Term term: termList) {
					s += " " + term.word;
				}
				textList.add(s.trim());
			}
			else {
				String notHanzi = buffer.toString();
				textList.add(notHanzi);
			}
		}
		return textList;
	}

	private static String handleDanwei(String text) {
		Pattern p = Pattern.compile("\\d\\s+(mm|cm|dm|m|km|KM|mg|Mg|g|kg|Kg|KG|m/s|kg/m|N|Pa|J|W|V)\\s+");
		Matcher m = p.matcher(text);
		while(m.find()) {
			int start = m.start();
			text = text.substring(0, start + 1) + text.substring(start + 2);
			m = p.matcher(text);
		}
		return text;
	}

	private static boolean containChinese(String s) {
		Matcher m = pat.matcher(s);
		return m.find();
	}

	/**
	 * 获得图片的Base64编码
	 * @param imgFile
	 * @return
	 */
	private static String getImageStr(File imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			if(in != null) {
				try {
					in.close();
				}
				catch(Exception e) {

				}
			}
		}
		// 对字节数组Base64编码
		return Base64.encode(data);
	}





}
